<?php

namespace App\Http\Controllers\Basic;

use App\Models\User;
use App\Models\UserWechat;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Payment\Order;
use EasyWeChat\Foundation\Application;

class WeixinController extends Controller
{
    //

    public function index(Request $request)
    {
        $app = new Application(config('wechat'));
        $userWechat = UserWechat::where('openid', $request->session()->get('userWechat.openid'))->first();
        //已登录
        if( !empty($userWechat) )
        {


            $isRelation = $userWechat->user_id;
            if($isRelation == 0)
            {
                return $this->bindPhonePage( $request->session()->get('userWechat.openid'));
            }else
            {
                return $this->indexPage();
            }

        }

        //未登录,并且不是回调,发起授权
        if( !($request->input('code')) )
        {
            $response = $app->oauth->scopes(['snsapi_userinfo'])->redirect();

            return $response;
        }


        //收到回调的授权
        $user = $app->oauth->user();

        $origin = $user->getOriginal();
        $token =  $user->getToken();

        $data['openid'] = $origin['openid'];
        $data['nickname'] = $origin['nickname'];
        $data['sex'] = $origin['sex'];
        $data['city'] = $origin['city'];
        $data['province'] = $origin['province'];
        $data['country'] = $origin['country'];
        $data['headimgurl'] = $origin['headimgurl'];
        $data['unionid'] = $origin['unionid'];

        $data['access_token'] = $token->access_token;
        $data['expires_in'] = $token->expires_in;
        $data['refresh_token'] = $token->refresh_token;
        $data['token_expires_time'] = date('Y-m-d H:i:s', time() + $token->expires_in);
        $data['refresh_token_expires_time'] = date('Y-m-d H:i:s', time() + 3600 * 24 * 30);

        $userWechat = UserWechat::where('openid', $origin['openid'])->first();

        if(!$userWechat)
        {
            $userWechat = new UserWechat();
        }

        $userWechat->fill($data);

        if($userWechat->save())
        {

            $request->session()->put('userWechat', $userWechat->attributesToArray());

            if($userWechat->user_id == 0)
            {
                return $this->bindPhonePage($origin['openid']);
            }else
            {
                return $this->indexPage();
            }
        }


    }


    public function bindPhonePage($key)
    {
        $data['key'] = $key;
        return view('wechat.bindPhone', $data);
    }


    public function indexPage()
    {
        $userWechat = UserWechat::where('openid', request()->session()->get('userWechat.openid'))->first();
        $userInfo = User::find( $userWechat->user_id);

        if(empty($userInfo))
        {
            Log::error('wechat login error');
            Log::error(request()->session()->get('userWechat'));

            return 'error!';
        }
        if(empty($userInfo->token))
        {
            $token = User::createToken();

            $userInfo->fill(['token'=>$token]);
            $userInfo->save();
        }

        $user['id'] = $userInfo->id;
        $user['nickname'] = $userInfo->nickname;
        $user['avatars'] = $userInfo->avatars;
        $user['realname'] = $userInfo->realname;
        $user['phone'] = $userInfo->phone;
        $user['token'] = $userInfo->token;

        request()->session()->put('user', $user);


        $content =  '<div style="text-align: center;
    margin-top: 30px;">
    <a  href="/api/weixin/pay"  style="font-size: 18px; color:#ffffff;background-color: #6e1581; width: 240px;text-align: center;line-height:40px;border-radius:20px;display: inline-block ">前往支付</a>

</div>';

        return response($content);//->cookie('token', $userInfo->token);
    }

    public function pay()
    {
        $userWechat = UserWechat::where('openid', request()->session()->get('userWechat.openid'))->first();
        $userInfo = User::find( $userWechat->user_id);

        if( empty($userInfo) )
        {
            return redirect(url('api/weixin'));
        }

        $data['token'] = $userInfo->token;

        return view('wechat.pay', $data);

    }

}
